package org.clipjoint.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.clipjoint.entity.User;
import org.clipjoint.entity.dto.UserDto;
import org.clipjoint.service.UserAdminService;
import org.clipjoint.service.impl.UserAdminServiceImpl;
import org.clipjoint.vo.JsonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 	图片验证码控制器
 * @author
 * date: 2021-1-11	
 *
 */
@WebServlet("/useradmin")
public class UserAdminController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private UserAdminService userService=new UserAdminServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");
		switch (method){
			case "list":
				list(request,response);
				break;
			case "add":
				add(request,response);
				break;
			case "deleteAll":
				deleteAll(request,response);
				break;
			case "del":
				del(request,response);
				break;
			case "updatePage":
				updatePage(request,response);
				break;
			case "update":
				update(request,response);
				break;
			case "excelUpload":
				excelUpload(request,response);
				break;
			case "addAll":
				addAll(request,response);
				break;
			case "createTimeStat":
				createTimeStat(request,response);
				break;
		}

	}
	//根据月份统计当月每天注册用户的数量
	private void createTimeStat(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取需要统计的月份
		Date date=null;
		try {
			date = new SimpleDateFormat("yyyy-MM").parse(request.getParameter("date"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//获取开始时间
		Date createTimeStart = date;
		//获取结束时间
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH,1);
		calendar.add(Calendar.MILLISECOND,-1);
		Date createTimeEnd = calendar.getTime();
		//查询本月注册的用户数据
		List<User> users = null;
		try {
			users = userService.list(UserDto.builder().createTimeStart(createTimeStart).createTimeEnd(createTimeEnd).build());
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		//日期集合
		List<Integer> days=new ArrayList<>();
		//人数集合
		List<Long> counts=new ArrayList<>();
		//初始化日期集合
		for (int i=1;i<=calendar.get(calendar.DAY_OF_MONTH);i++){
			days.add(i);
		}
		//初始化人数集合
		for (int i=1;i<=calendar.get(calendar.DAY_OF_MONTH);i++){
			counts.add(0l);
		}
		//遍历日期
		for (Integer day: days) {
			//遍历用户集合
			for (User user:users) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(user.getCreate_time());
				int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
				if (dayOfMonth==day){
					counts.set(day-1,counts.get(day-1)+1);
				}
			}

		}
		//使用map集合封装结果
		Map<String , Object> map=new HashMap<>();
		map.put("days",days);
		map.put("counts",counts);
		//返回统计结果
		response.getWriter().print(JsonResult.builder().code(0).data(map).build().toJsonString());

	}

	//批量保存
	private void addAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取用户列表的json字符串
		String usersJson = request.getParameter("users");
		//将json字符串解析为User集合
		List<User> users = JSON.parseArray(usersJson, User.class);
		int result = userService.addAll(users);
		if(users.size()==result){
			response.getWriter().print(JsonResult.builder().code(0).msg("成功导入条"+result+"数据").build().toJsonString());
		}
		else if(result !=0){
			response.getWriter().print(JsonResult.builder().code(0).msg("成功导入"+result+"条，失败"+(users.size()-result)+"条").build().toJsonString());
		}else {
			response.getWriter().print(JsonResult.builder().code(1).msg("导入失败").build().toJsonString());
		}

	}

	//Excel文件上传解析
	private void excelUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1.创建磁盘文件项工厂对象
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 2.创建一个servlet文件上传处理对象
		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

		// 3.解析request对象
		List<FileItem> fileItems = new ArrayList<>();
		try {
			fileItems = servletFileUpload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		//遍历文件项
		for(FileItem fileItem:fileItems){
			//只处理文件字段
			if (!fileItem.isFormField()){
				//获取服务器保存目录的真实路径
				String realPath = request.getServletContext().getRealPath("WEB-INF/upload/excel/");
				//随机生成文件名
				String saveName= UUID.randomUUID().toString()+"-"+fileItem.getName();
				try {
					//保存文件
					fileItem.write(new File(realPath+File.separator+saveName));

					//解析Excel文件
					ExcelReader reader = ExcelUtil.getReader(realPath+File.separator+saveName);
					List<User> result = reader.readAll(User.class);

					request.getSession().setAttribute("result",JSON.toJSONString(result));
					//返回上传成功结果
					response.getWriter().print(JsonResult.builder().code(0).msg("上传成功").data(result).build().toJsonString());
					return;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		//返回上传失败结果
		response.getWriter().print(JsonResult.builder().code(1).msg("上传失败").build().toJsonString());


	}

	//修改信息
	private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Long id = Long.valueOf(request.getParameter("id"));
		String username = request.getParameter("username");
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		Long credit = Long.valueOf(request.getParameter("credit"));
		Long account = Long.valueOf(request.getParameter("account"));
		//调用service保存数据
		int result= 0;
		try {
			result = userService.update(User.builder().id(id).credit(credit).account(account).username(username).email(email).password(password).build());
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		//判断结果
		if(result==1){
			response.getWriter().print(JsonResult.builder().code(0).msg("修改成功").build().toJsonString());
		}else{
			response.getWriter().print(JsonResult.builder().code(1).msg("修改失败").build().toJsonString());
			return;
		}
	}

	//跳转到修改页面
	private void updatePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取用户id
		Long id = Long.valueOf(request.getParameter("id"));
		User user= null;
		try {
			user = userService.getOneById(id);
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		//转发到修改页面
		request.setAttribute("user",user);
		request.getRequestDispatcher("/user/update.jsp").forward(request,response);
	}

	private void del(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取id
		Long id = Long.valueOf(request.getParameter("id"));
		int result = 0;
		try {
			result = userService.del(id);
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		if(result==1){
			response.getWriter().print(JsonResult.builder().code(0).msg("删除成功").build().toJsonString());
		}
		else {
			response.getWriter().print(JsonResult.builder().code(1).msg("删除失败").build().toJsonString());
		}
	}

	private void deleteAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取id数组的json字符串
		String idsJSON= request.getParameter("ids");
		//将json字符串转为List集合
		List<Long> ids = JSON.parseArray(idsJSON, Long.class);

		//调用service删除所有数据
		int result = userService.deleteAll(ids);
		if(ids.size()==result){
			response.getWriter().print(JsonResult.builder().code(0).msg("全部删除成功").build().toJsonString());
		}
		else if(result !=0){
			response.getWriter().print(JsonResult.builder().code(0).msg("成功删除"+result+"条，失败"+(ids.size()-result)+"条").build().toJsonString());
		}else {
		response.getWriter().print(JsonResult.builder().code(1).msg("删除失败").build().toJsonString());
		}

	}

	//添加用户
	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
	//获取请求参数
		String username = request.getParameter("username");
		String email = request.getParameter("email");
		String password = request.getParameter("password");

		//调用service保存数据
		int result= 0;
		try {
			result = userService.add(User.builder().username(username).email(email).password(password).build());
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		//判断结果
		if(result==1){
			response.getWriter().print(JsonResult.builder().code(0).msg("添加成功").build().toJsonString());
		}else{
			response.getWriter().print(JsonResult.builder().code(1).msg("添加失败").build().toJsonString());
			return;
		}
	}

	//获取用户信息列表
	private void list(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取分页参数
		Integer page = Integer.valueOf(request.getParameter("page"));
		Integer limit = Integer.valueOf(request.getParameter("limit"));

		//获取排序参数和排序方式
		String orderField = request.getParameter("orderField");
		String orderType = request.getParameter("orderType");
		//获取查询条件
		String nickname = request.getParameter("nickname");
		String username = request.getParameter("username");
		String email = request.getParameter("email");
		//封装dto
		UserDto userDto = UserDto.builder()
				.page(page).limit(limit)
				.orderField(orderField)
				.orderType(orderType)
				.nickname(nickname)
				.username(username)
				.email(email)
				.build();

		//获取日期时间区间字符串
		String createTimeRange = request.getParameter("createTimeRange");
		if (createTimeRange!=null){
			String[] createTimeArray = createTimeRange.split(" - ");
			try {
				userDto.setCreateTimeStart(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTimeArray[0]));
				userDto.setCreateTimeEnd(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTimeArray[1]));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		//调用service获取用户数据
		List<User> list= null;
		try {
			list = userService.list(userDto);
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}

		//调用service获取用户总数据量
		Long count = null;
		try {
			count = userService.count(userDto);
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}

		//判断结果
		if (list == null || count==null){
			response.getWriter().print(JsonResult.builder().code(1).msg("查询错误").build().toJsonString());
			return;
		}
		//封装结果返回
		response.getWriter().print(JsonResult.builder().code(0).count(count).data(list).build().toJsonString());


	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
